//
//  CustomScrollView.m
//  Movie
//
//  Created by 路贵斌 on 15/11/7.
//  Copyright © 2015年 huazi. All rights reserved.
//

#import "CustomScrollView.h"

#import "TopHotMovieEntity.h"

#define MaxItemNum 6

@interface CustomScrollView ()<UIScrollViewDelegate>

@property (nonatomic, weak) IBOutlet UIScrollView   *scrollView;
@property (nonatomic, weak) IBOutlet UIPageControl  *pageControl;
@property (nonatomic, strong) NSMutableArray        *dataSource;

@end


@implementation CustomScrollView

- (void)awakeFromNib
{
    self.frame = CGRectMake(0, 0, DeviceWidth, 95);
    self.scrollView.delegate = self;
    for (int i = 0; i < MaxItemNum + 2; i ++) {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i+100;
        btn.frame = CGRectMake(DeviceWidth * i, 0, DeviceWidth, self.height);
        [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self .scrollView addSubview:btn];
    }
    
}

- (void)resetScrollViewWithArray:(NSMutableArray *)array
{
    if (!array || array.count == 0) return;
    
    self.dataSource = [NSMutableArray arrayWithArray:array];
    [self.dataSource insertObject:array[array.count -1] atIndex:0];
    [self.dataSource addObject:array[0]];
    
    int i = 0;
    for (TopHotMovieEntity *entity in self.dataSource) {
        if (i >= MaxItemNum +2) break;
        UIButton * btn = (UIButton *)[self.scrollView viewWithTag:i+100];
        [btn sd_setBackgroundImageWithURL:[NSURL URLWithString:entity.moviePicture] forState:UIControlStateNormal];
        i++;
    }
    
    self.pageControl.numberOfPages = self.dataSource.count -2;
    self.scrollView.contentSize = CGSizeMake(DeviceWidth * self.dataSource.count, 0);
    self.scrollView.contentOffset = CGPointMake(DeviceWidth, 0);
    self.pageControl.currentPage = 0;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x == scrollView.contentSize.width - DeviceWidth) {
        [scrollView setContentOffset:CGPointMake(DeviceWidth, 0) animated:NO];
    }else if (scrollView.contentOffset.x == 0){
        [scrollView setContentOffset:CGPointMake(scrollView.contentSize.width - DeviceWidth * 2, 0) animated:NO];
    }
    
    self.pageControl.currentPage = scrollView.contentOffset.x / DeviceWidth - 1;
}


- (void)btnClicked:(UIButton *)btn
{
    NSLog(@"跳转详情页");
}

@end
